package xin.alum.aim.redis;

import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.data.redis.connection.MessageListener;
import xin.alum.aim.Aim;
import xin.alum.aim.groups.SessionGroups;
import xin.alum.aim.groups.Sessions;
import xin.alum.aim.model.Events;
import xin.alum.aim.model.Transportable;
import xin.alum.aim.util.JSONUtils;

/**
 * @author Alum(alum @ live.cn)
 * @date 2021/8/17 20:01
 */
class ReplyMessageListener implements MessageListener {

   private final SessionGroups groups;

   private final Sessions sessions;

    ReplyMessageListener(SessionGroups groups,Sessions sessions) {
        this.groups = groups;
        this.sessions=sessions;
    }

    @Override
    public void onMessage(org.springframework.data.redis.connection.Message redisMessage, byte[] bytes) {
        if (Aim.message != null) {
            Aim.message.onMessage(redisMessage.getBody());
        } else {
            Transportable events = JSONUtils.fromJson(redisMessage.getBody(), new TypeReference<Events>() {});
            if (events.getRecipient() == null || events.getRecipient().isEmpty() || events.getRecipient().equals(Sessions.ALL_SESSIONS)) {
                sessions.sends(events);
            } else {
                groups.get(events.getRecipient()).sends(events);
            }
        }
    }
}
